﻿using System;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.IO;

namespace hxweditor
{

	//地形切割时暂不考虑地形问题
	public class SceneFormationEditor:BaseEditorWindow<SceneFormationEditor>
	{
		//场景列表根目录
		string sceneRootPathKey = "SceneFormationEditor_sceneRootPath";
		string sceneRootPath = "";
		//输出目录
		string sceneOutputPathKey = "SceneFormationEditor_sceneOutputPath";
		string sceneOutputPath = "";
		//场景名
		string sceneNameKey = "SceneFormationEditor_sceneName";
		string sceneName = "";
		//行数
		string sceneRowKey = "SceneFormationEditor_row";
		int row = 10;
		//列数
		string sceneColumnKey = "SceneFormationEditor_column";
		int column = 10;
        //动态加载范围默认1圈
        string sceneRangeKey = "SceneFormationEditor_range";
        int range = 1;


        //场景加载脚本
        private SceneLoadManager loader;
        //场景分割数据
        private SceneFormatVo formatVo;

		//场景unti3yd完整路径
		private string scenePath{
			get{
				string fullpath = sceneRootPath + "\\" + sceneName + "\\" + sceneName + ".unity";
				return PathTool.RemoveTo (fullpath,PathTool.AssetsFlag);
			}
		}

		//场景绝对路径
		private string fullScenePath{
			get{
				string fullpath = sceneRootPath + "\\" + sceneName + "\\" + sceneName + ".unity";
				return PathTool.FormationPath (fullpath);
			}
		}

		//需要切分的场景元素
		private List<GameObject> sceneObjList = new List<GameObject> ();
		//灯光，相机节点
		private List<GameObject> configObjList = new List<GameObject> ();

		private Dictionary<string,List<GameObject>> saveSceneList = new Dictionary<string, List<GameObject>>();

        private GameObject configObj = null;

		SceneFormationEditor()
		{
			this.titleContent = new GUIContent("格式化场景编辑器");
		}

		void OnEnable(){
			sceneRootPath = PlayerPrefs.GetString (sceneRootPathKey,"请输入列表根目录");
			sceneOutputPath = PlayerPrefs.GetString (sceneOutputPathKey,"请输入列表根目录");
			sceneName = PlayerPrefs.GetString (sceneNameKey,"请输入场景名");
			row = PlayerPrefs.GetInt (sceneRowKey,10);
			column = PlayerPrefs.GetInt (sceneColumnKey,10);
            range = PlayerPrefs.GetInt(sceneRangeKey, 1);
		}

		void OnDisable(){
			PlayerPrefs.SetString (sceneRootPathKey,sceneRootPath);
			PlayerPrefs.SetString (sceneOutputPathKey,sceneOutputPath);
			PlayerPrefs.SetString (sceneNameKey,sceneName);
			PlayerPrefs.SetInt (sceneRowKey,row);
			PlayerPrefs.SetInt (sceneColumnKey,column);
            PlayerPrefs.SetInt(sceneRangeKey, range);
		}

		void OnGUI(){
			
			sceneRootPath = ShowInputString ("请输入场景列表的根目录:", sceneRootPath);

			sceneOutputPath = ShowInputString ("请输入输出目录:",sceneOutputPath);

			ShowSpaceLine (1);

			sceneName = ShowInputString ("请输入场景名:",sceneName);

			if (ShowButton ("浏览")) {
				OpenFileName file = WindowDll.GetDefault (sceneRootPath);
				if (WindowDll.GetOpenFileName (file)) {
					string fileName = FileTool.GetFileName (file.fileTitle);
					if (fileName != "")
						sceneName = fileName;
					FocusThis ();
				}
			}

			ShowSpaceLine (1);

			row = ShowInputInt ("请输入行数:",row);
			column = ShowInputInt ("请输入列数",column);
            range = ShowInputInt("动态加载范围",range);

			ShowSpaceLine (3);

			if (ShowButton ("打开场景")) {
				OpenSelectScene ();
			}

			if (ShowButton ("删除旧数据")) {
				PathTool.RemoveFile (sceneOutputPath + @"/" + sceneName);
			}

			if (ShowButton ("开始切割保存")) {

				//判断目标场景是否打开
				if (EditorSceneManager.sceneCount == 1 && EditorSceneManager.GetSceneAt (0).name == sceneName) {
					
				} else {
					OpenSelectScene ();
				}
				//分类好场景资源
				classify ();
				//构建场景列表
				buildSceneList ();
				//保存场景
				SaveScene ();
			}

		}



        //把场景元素分类
        private void classify()
        {
            if (configObj != null)
            {
                GameObject.DestroyImmediate(configObj);
            }

            configObj = new GameObject(configName);
            configObjList.Add(configObj);

            formatVo = configObj.AddComponent<SceneFormatVo>();

            for (int i = sceneObjList.Count - 1; i >= 0; i--)
            {
                GameObject obj = sceneObjList[i];
                if (obj.GetComponent<Light>() != null || obj.GetComponent<Camera>() != null)
                {
                    sceneObjList.RemoveAt(i);
                    obj.transform.SetParent(configObj.transform);
                }
            }

        }

        private string configName
        {
            get
            {
                return sceneName.ToLower() + "_config";
            }
        }

		//构建场景列表
		private void buildSceneList(){

            Vector4 bounds = getSceneBounds();

			saveSceneList = new Dictionary<string, List<GameObject>> ();
            saveSceneList[configName] = new List<GameObject>();
			foreach (GameObject obj in configObjList) {
                saveSceneList[configName].Add(obj);
			}

			foreach (GameObject obj in sceneObjList) {
                Vector3 grid = SceneTool.GetGrid(obj.transform.position, bounds, row, column);
				string key = sceneName + grid.x + "_" + grid.y;
				if (!saveSceneList.ContainsKey (key)) {
					saveSceneList [key] = new List<GameObject> ();
				}
				saveSceneList [key].Add (obj);
			}

            formatVo.bounds = bounds;
            formatVo.row = row;
            formatVo.column = column;
            formatVo.sceneName = sceneName;
            formatVo.range = range;
		}

        //保存场景
        private void SaveScene()
        {
            //先删除该保存目录
            PathTool.RemoveFile(sceneOutputPath + @"/" + sceneName);

            var num = saveSceneList.GetEnumerator();
            while (num.MoveNext())
            {
                Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
                foreach (GameObject obj in num.Current.Value)
                {
                    EditorSceneManager.MoveGameObjectToScene(obj, scene);
                }
                string outPath = sceneOutputPath + @"/" + sceneName + @"/" + num.Current.Key + ".unity";
                outPath = PathTool.RemoveTo(outPath, PathTool.AssetsFlag);
                EditorSceneManager.SaveScene(scene, outPath);
            }
        }


		//打开选择的场景
		private void OpenSelectScene(){
			if (File.Exists (fullScenePath)) {
				EditorSceneManager.OpenScene (scenePath,OpenSceneMode.Single);
				sceneObjList.Clear ();
				GameObject[] objects = GameObject.FindObjectsOfType<GameObject> ();
				sceneObjList = new List<GameObject>( objects);
				configObjList = new List<GameObject> ();
			}
		}

		//拿到场景的包围区间
		private Vector4 getSceneBounds(){

			float minx = 0;

			float maxx = 0;

			float minz = 0;

			float maxz = 0;

			foreach (GameObject obj in sceneObjList) {

				if (obj.transform.position.x < minx) {
					minx = obj.transform.position.x;
				}else if(obj.transform.position.x > maxx){
					maxx =  obj.transform.position.x;
				}

				if (obj.transform.position.z < minz) {
					minz = obj.transform.position.z;
				}else if(obj.transform.position.z > maxz){
					maxz = obj.transform.position.z;
				}
			}

			return new Vector4 (minx,maxx,minz,maxz);
		}


	}
}

